﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using WeigSystem.Class;

namespace WeighSystem.Class
{
    public class SoapConnection
    {
        /*********************************************************************************************************/
        //字段名	       参数意义	   参数类型及长度	  数据格式	                               备注
        //BoxCode          入库单号    nvarchar2(30)      908C79020002;908C79020003;908C79020005    一箱有多个标签
        //BoxCodeWeight    重量        number(20,2)        999.999
        /*********************************************************************************************************/
        //字段名           参数意义    参数类型及长度                备注
        //ErrorCode        消息类型    nvarchar2(5)         S        S成功E失败
        //ErrorMessage     错误内容    nvarchar2(100)      成功
        /*********************************************************************************************************/


        /// <summary>
        /// 发送SOAP请求，并返回响应xml
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="datastr">SOAP请求信息</param>
        /// <returns>返回响应信息</returns>
        public static string GetSOAPReSource(string url, string datastr)
        {

            //发起请求
            Uri uri = new Uri(url);
            WebRequest webRequest = WebRequest.Create(uri);
            webRequest.ContentType = "application/soap+xml; charset=utf-8";
            webRequest.Method = "POST";
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                byte[] paramBytes = Encoding.UTF8.GetBytes(datastr.ToString());
                requestStream.Write(paramBytes, 0, paramBytes.Length);
            }

            //响应
            WebResponse webResponse = webRequest.GetResponse();
            webRequest.Timeout = 5000;
            using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
            {
                string result = "";
                return result = myStreamReader.ReadToEnd();
            }
        }
        static public S_RetMessage WebStartRequest(string connectiostring,string code,string weigh,string funName = "WeighSystem")
        {
            //构造soap请求信息
            //https://www.cnblogs.com/tiancai/p/9620189.html
            S_RetMessage retMsg = new S_RetMessage();
            retMsg.localError = EnumRet.ERROR_FROMSERVER;
            StringBuilder soap = new StringBuilder();
            soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            soap.Append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
            soap.Append("<soap12:Body>");
            soap.Append("<WeighSystem xmlns = \"http://tempuri.org/\" >");
            soap.Append(string.Format("<boxCodes> {0} </boxCodes>", code));
            soap.Append(string.Format("<Weigh> {0} </Weigh>", weigh));
            soap.Append("</WeighSystem>");
            soap.Append("</soap12:Body>");
            soap.Append("</soap12:Envelope>");
            if (!connectiostring.Contains("http")/* || !connectiostring.Contains("WeighingVerifyWebService")*/) // change to http://192.168.98.87:8033/WeighingVerifyWebService.asmx?wsdl
            {
                //"http://localhost:50174/AGVWebService.asmx";
                retMsg.localError = EnumRet.ERROR_URL;
                return retMsg;
            }
            string url = connectiostring.Trim();
            var response = GetSOAPReSource(url, soap.ToString());
            FileLog.WriteLogToFile(FileLog.LOGLEVEL.信息, "收到:" + response);
            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(response);
            /*
            XmlNode xxNode = xdoc.SelectSingleNode("/users/user[1]");

            foreach (XmlNode xxNode2 in xxNode.ChildNodes)
            {
                Console.WriteLine(xxNode2.Name + "---" + xxNode2.InnerText);
            }
            */

            XmlNodeList list = xdoc.GetElementsByTagName("WeighSystemResult");

            Console.WriteLine(list[list.Count - 1].FirstChild.Value);

            retMsg.messager = list[list.Count - 1].ChildNodes[0].InnerText;
            retMsg.status = list[list.Count - 1].ChildNodes[1].InnerText;
            if (retMsg.status == "S" || retMsg.status == "OK")
                retMsg.localError = EnumRet.SUCCESS;
            /*
            foreach (XmlNode item in list)
            {
                if (item.InnerText.Contains("S") || item.InnerText.Contains("OK"))
                { }
                //MessageBox.Show(item.InnerText);
                //Console.WriteLine(item.InnerText);
            }
            */
            return retMsg;
        }

        static public S_RetMessage WebStartRequestTest(string connectiostring, string code, string weigh, string funName = "WeighSystem")
        {
            //构造soap请求信息
            //https://www.cnblogs.com/tiancai/p/9620189.html
            S_RetMessage retMsg = new S_RetMessage();
            StringBuilder soap = new StringBuilder();
            soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            soap.Append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
            soap.Append("<soap12:Body>");
            soap.Append("<WeighSystem xmlns = \"http://tempuri.org/\" >");
            soap.Append(string.Format("<boxCodes> {0} </boxCodes>", code));
            soap.Append(string.Format("<Weigh> {0} </Weigh>", weigh));
            soap.Append("</WeighSystem>");
            soap.Append("</soap12:Body>");
            soap.Append("</soap12:Envelope>");
            if (!connectiostring.Contains("http")/* || !connectiostring.Contains("WeighingVerifyWebService")*/) // change to http://192.168.98.87:8033/WeighingVerifyWebService.asmx?wsdl
            {
                //"http://localhost:50174/AGVWebService.asmx";
                MessageBox.Show("请输入正确的服务地址！");
                retMsg.localError = EnumRet.ERROR_URL;
                return retMsg;
            }
            string url = connectiostring.Trim();
            var response = GetSOAPReSource(url, soap.ToString());
            FileLog.WriteLogToFile(FileLog.LOGLEVEL.信息, "收到:" + response);
            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(response);
            /*
            XmlNode xxNode = xdoc.SelectSingleNode("/users/user[1]");

            foreach (XmlNode xxNode2 in xxNode.ChildNodes)
            {
                Console.WriteLine(xxNode2.Name + "---" + xxNode2.InnerText);
            }
            */

            XmlNodeList list = xdoc.GetElementsByTagName("WeighSystemResult");

            retMsg.messager = list[list.Count - 1].ChildNodes[0].InnerText;
            retMsg.status = list[list.Count - 1].ChildNodes[1].InnerText;
            if (retMsg.status == "S" || retMsg.status == "OK")
                retMsg.localError = EnumRet.SUCCESS;

            /*
            foreach (XmlNode item in list)
            {
                if (item.InnerText.Contains("S") || item.InnerText.Contains("OK"))
                { }
                //MessageBox.Show(item.InnerText);
                //Console.WriteLine(item.InnerText);
            }
            */
            return retMsg;
        }

    }
}
